package server.views.servermngpanel.toppanel;

import java.awt.BorderLayout;
import java.awt.Color;
//import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.swing.AbstractAction;
//import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
//import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;

//import common.message.Message;
import common.message.serverSend.ForceUserLogoutMsg;
import common.types.StatusType;
import server.config.Public;
import server.utils.ServerUtils;
//import server.views.MyTableModel;
import server.views.ServerMain;
import server.doc.xml.*;
import server.models.UserProfile;
import server.network.*;


public class TopPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5337830514771311088L;

	private boolean runServer = true; // 0 表示开启服务，1表示关闭服务

	private JButton startBtn = new JButton("开启服务");
	
	private static JTextArea detailJt = new JTextArea(5,5);//中部面板信息

	private JButton LogOutBtn = new JButton("强制下线");

	private Thread myThread = null;

	private XMLUserProfile xmlProfile = XMLUserProfile.getInstance();

//	private HashMap h=new HashMap();
	
//	private JDialog dialog;
	
	public TopPanel(){
		
	}
	

	
	public TopPanel(final ServerMain f) {
		
		this.setLayout(new BorderLayout());
		this.setBorder(new TitledBorder("操作与日志"));
		JPanel jp = new JPanel();
		jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
		startBtn.setBackground(Color.red);
		jp.add(startBtn);
		jp.add(LogOutBtn);
		this.add(jp,BorderLayout.WEST);
		detailJt.setEditable(false); 
		detailJt.setBackground(Color.white);
		detailJt.setForeground(Color.BLUE);
	
		JScrollPane   scrollPane   =   new   JScrollPane(detailJt);
		this.add(scrollPane,BorderLayout.CENTER);	
		readLog();

		// 强制下线按钮不可用状态
		LogOutBtn.setEnabled(false);
		// 开启按钮
		startBtn.addActionListener(new AbstractAction() {

			private static final long serialVersionUID = 2814927902762576011L;

			public void actionPerformed(ActionEvent e) {
				ServerThread serverThread;
				if (runServer) {
					// 开启服务创建一个服务线程
					int port = 8080;
					try {
						port = Integer.parseInt(ServerUtils.properties.getProperty("ServerSocketPort","8080"));
						Public.serverSocket = new ServerSocket(port);
					} catch (BindException e1) {
						setTShow(Integer.toString(port),3);
						//JOptionPane.showMessageDialog(f, "该端口已绑定！", "提示框",
								//JOptionPane.WARNING_MESSAGE);
						return;
					} catch (IOException e1) {
						e1.printStackTrace();
					}

					serverThread = new ServerThread(Public.stop, f);
					myThread = new Thread(serverThread);
					myThread.start();
					
					setTShow("",1);
					
					//chatAllBtn.setEnabled(true);
					
					startBtn.setText("关闭服务");
					runServer = false;
				} else {
					//更新显示在服务器端的上线用户信息
					ArrayList<ArrayList<String>> profileList = new ArrayList<ArrayList<String>>();
					for (Integer uid : Public.status.getOnlineUsers()) {
						ArrayList<String> strProfile = new ArrayList<String>();
						UserProfile profile = xmlProfile.getUser(uid.intValue());
						strProfile.add(Integer.toString(profile.getUserID()));	// userID
						strProfile.add(profile.getName());						// nick name
						strProfile.add(profile.getGender().toString());			// gender
						strProfile.add(Public.dateFormat.format(Public.status.getOnlineTime(uid.intValue())));
																				// online time
						profileList.add(strProfile);
					}
					f.getServerMngPanel().getTablePanel().getDataModel().setData(profileList);
					Public.serverClose();
					
					
					Public.stop = true;
					myThread.interrupt();// 终止线程
					try {
						if (Public.serverSocket != null)
							Public.serverSocket.close();
					} catch (IOException e1) {
						return;
					} catch (Exception e1) {
						return;
					}
					//清空Public.mySocketInfo里存的客户端的信息
					Public.clientIStream.clear();
					Public.clientOStream.clear();
					Public.clientSocket.clear();
					Public.clientThreads.clear();
					setTShow("",2);
					LogOutBtn.setEnabled(false);
					
					//chatAllBtn.setEnabled(false);
					
					startBtn.setText("开启服务");
					runServer = true;
				}
			}
		});
		
		
		// 强制下线
		LogOutBtn.addActionListener(new AbstractAction() {

			private static final long serialVersionUID = -4064778637335993867L;

			public void actionPerformed(ActionEvent e) {
				// 选中某个用户，点击，强制其下线，发下线包
				// 选中行的个数
				int rowCount = f.getServerMngPanel().getTablePanel().getTable().getSelectedRowCount();
				System.out.println(rowCount);
				//取到所有选中行的索引数组
				int[] rows= f.getServerMngPanel().getTablePanel().getTable().getSelectedRows();
				
				int userID;
//				System.out.println(rows.length);
				// 循环遍历
				for (int i = 0; i < rows.length; i++) {
					//取用户编号
					System.out.println(rows[i]);
					userID = Integer.parseInt(f.getServerMngPanel().getTablePanel().getDataModel().getValueAt(rows[i], 0));
					System.out.println(userID);
					//打包下线包
					ForceUserLogoutMsg forceLogoutPacket = new ForceUserLogoutMsg(userID);
					try {
						//取出用户编号对应的输出流，发给客户端下线包
						//给客户端发下线包
						Integer uid = new Integer(userID);
						ObjectOutputStream oos = Public.clientOStream.get(uid);
						oos.writeObject(forceLogoutPacket);
						oos.flush();
						//将用户在线标志改为0
						Public.clientIStream.remove(uid);
						Public.clientOStream.remove(uid);
						Public.clientSocket.remove(uid);
						Public.clientThreads.remove(uid);
						Public.status.setStatus(uid, StatusType.offline);
						setTShow(uid.toString(),0);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				
				//更新显示在服务器端的上线用户信息
				ArrayList<ArrayList<String>> profileList = new ArrayList<ArrayList<String>>();
				for (Integer uid : Public.status.getOnlineUsers()) {
					ArrayList<String> strProfile = new ArrayList<String>();
					UserProfile profile = xmlProfile.getUser(uid.intValue());
					strProfile.add(Integer.toString(profile.getUserID()));	// userID
					strProfile.add(profile.getName());						// nick name
					strProfile.add(profile.getGender().toString());			// gender
					strProfile.add(Public.dateFormat.format(Public.status.getOnlineTime(uid.intValue())));
																			// online time
					profileList.add(strProfile);
				}
				f.getServerMngPanel().getTablePanel().getDataModel().setData(profileList);				
				
				LogOutBtn.setEnabled(false);
			}
		});
	}

	
//	把日期转化为字符串
	public static String dateToStr(Date date,String format)
	{
		SimpleDateFormat f = new SimpleDateFormat(format);
		f.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		return f.format(date);
		
	}  
	/**
	 * 显示日志
	 * @param s
	 * @param type
	 * 1账号["+s+"]于：		"+date+"	被服务器强制下线
	 * 2服务开启于："+date
	 * 3启动服务失败该"+s+" 端口已绑定
	 * 4账号["+s+"]于："+date+"上线了
	 * 5账号["+s+"]于："+date+"下线了
	 * 6在线账号["+s+"]于：		"+date+"	被服务器删除了并被迫下线
	 * 7不在线账号["+s+"]于：		"+date+"	被服务器删除了
	 * 8程序于："+date+" 退出了
	 */
	public static void setTShow(String s,int type){
		
		SimpleDateFormat sdf = new SimpleDateFormat(
		"yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		String date = sdf.format(new Date());
		
		//Calendar
		if (type == 0){
			detailJt.append("账号["+s+"]于：		"+date+"	被服务器强制下线");
		}else if (type == 1){
			detailJt.append("服务开启于："+date);
		}else if (type == 2){
			detailJt.append("服务关闭于："+date);
		}else if (type == 3){
			detailJt.append("启动服务失败该"+s+" 端口已绑定");
		}else if (type == 4){
			detailJt.append("账号["+s+"]于："+date+"上线了");
		}else if (type == 5){
			detailJt.append("账号["+s+"]于："+date+"下线了");
		}else if (type == 6){
			detailJt.append("在线账号["+s+"]于：		"+date+"	被服务器删除了并被迫下线");
		}else if (type == 7){
			detailJt.append("不在线账号["+s+"]于：		"+date+"	被服务器删除了");
		}else if (type == 8){
			detailJt.append("程序于："+date+" 退出了");
		}
		
	
		detailJt.append("\n");
		
		detailJt.setCaretPosition( detailJt.getDocument().getLength());


	}
	
	
	/**
	 * 返回当前日期
	 * @return 当前日期
	 */
	public String getCurDate(){
		SimpleDateFormat sdf = new SimpleDateFormat(
		"yyyy-MM-dd");
//		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		return sdf.format(new Date());
	}
	
	/**
	 * 判断日志是否存在
	 */
	public int logExist(){
		File logFile = new File("./log/" + getCurDate() +".txt");
		if(logFile.exists()){
			return 1;

		}else{
			return 0;

		}
	}
	
	public int readLog(){
		
		if (logExist() < 1){
			
			writeLog();
			
			return 0;
		}
		
		String   str   =   null;   
 
		
		BufferedReader Reader = null;
		try {
			Reader = new   BufferedReader(new   FileReader("./log/" + getCurDate() +".txt"));
			while(true){   
				str   =   Reader.readLine();   

				if   (str   ==   null)     break;  
				detailJt.append(str);
				detailJt.append("\n");
				   
			}  
			if (str == null) return -1;
			
			
			
			return 1;
			//detailJt.append("\n");
			
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
			return 0;
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
			return 0;
		}finally{
			try {
				Reader.close();
			} catch (IOException e) {
				// TODO 自动生成 catch 块
				e.printStackTrace();
			}  
			
		}
	}
	
	public int writeLog(){
		//   写   ---------------------------------------------------   
		FileWriter Writer = null;
		try {
			Writer = new   FileWriter("./log/" + getCurDate() +".txt");
			Writer.write(detailJt.getText());  
			
			Writer.flush();
			return 1;
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
			return 0;
		}finally{
			
			try {
				Writer.close();
			} catch (IOException e) {
				// TODO 自动生成 catch 块
				e.printStackTrace();
			}   
			
		}
		
		
		
		//--------------------------------------------------- 
	}


	public JButton getLogOutBtn() {
		return LogOutBtn;
	}

	public void setLogOutBtn(JButton logOutBtn) {
		LogOutBtn = logOutBtn;
	}

	public boolean getRunServer() {
		return runServer;
	}

	public void setServer(boolean server) {
		this.runServer = server;
	}

	public JButton getStartBtn() {
		return startBtn;
	}

	public void setStartBtn(JButton startBtn) {
		this.startBtn = startBtn;
	}

	public JTextArea getDetailJt() {
		return detailJt;
	}
}
